package com.cinema.util;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 日志管理工具类（单例模式）
 */
public class LogManager {
    private static LogManager instance;
    private final String LOG_FILE = "src/main/resources/logs/system.log";
    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private LogManager() {
        // 确保日志目录存在
        try {
            java.nio.file.Files.createDirectories(java.nio.file.Paths.get("src/main/resources/logs/"));
        } catch (IOException e) {
            System.err.println("⚠️ 日志目录创建失败：" + e.getMessage());
        }
    }

    public static LogManager getInstance() {
        if (instance == null) {
            synchronized (LogManager.class) {
                if (instance == null) {
                    instance = new LogManager();
                }
            }
        }
        return instance;
    }

    /**
     * 写入日志
     * @param content 日志内容
     * @param operator 操作人
     */
    public void writeLog(String content, String operator) {
        String log = String.format("[%s] 操作人：%s - %s%n",
                LocalDateTime.now().format(formatter), operator, content);

        try (PrintWriter out = new PrintWriter(new FileWriter(LOG_FILE, true))) {
            out.write(log);
        } catch (IOException e) {
            System.err.println("❌ 日志写入失败：" + e.getMessage());
        }
    }
}
